﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Windows.Foundation;
using Windows.Phone.Speech.Recognition;
using Windows.Phone.Speech.Synthesis;

namespace Tyloo
{
    public partial class SearchResult : PhoneApplicationPage
    {

        //
        // Code behind for the Magic Memo sample application Main page
        //
        #region Speech objects

        // Speech synthesizer for prompting and confirming
        private SpeechSynthesizer speechOutput;

        // Speech Recognzier for entering memos using the default dictation grammar
        private SpeechRecognizerUI speechInput;

        // Speech Recognizer for getting user commands. Uses mainPageCommands to add a list grammar
        private SpeechRecognizerUI commandReco;

        // List of commands to listen for on the mainpage
        private List<string> mainPageCommands = new List<string>();

        #endregion

        #region Private fields

        // File in isostorage to store memos
        private string fileName = "savedMemos.txt";

        // Uri of the other application page
        private Uri viewMemosUri = new Uri("/ViewMemos.xaml", UriKind.Relative);

        private int numMemosSaved = 0;

        #endregion
        public SearchResult()
        {
            InitializeComponent();
            InitializeSpeech();
            InitializeCommandGrammar();
            if (PhoneApplicationService.Current.State.ContainsKey("Search"))
            {
                string cari = (string)PhoneApplicationService.Current.State["Search"];
                System.Diagnostics.Debug.WriteLine(cari);
            }

        }

        private void ResultChange(object sender, SelectionChangedEventArgs e)
        {
            PhoneApplicationService.Current.State["Item"] = ResultBox.SelectedItem;
            NavigationService.Navigate(new Uri("/NewsViewer.xaml", UriKind.Relative));
        }
        private void appBarChange(object sender, ApplicationBarStateChangedEventArgs e)
        {

        }

        private void homeClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Home.xaml?", UriKind.Relative));
        }
        private void searchClickHandler(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SearchResult.xaml", UriKind.Relative));
        }
        private void bookmarksClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Home.xaml?goto=1", UriKind.Relative));
        }
        private void recentClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Home.xaml?goto=2", UriKind.Relative));
        }
        private void infoClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Home.xaml?goto=3", UriKind.Relative));

        }
        private void aboutClickHandler(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/About.xaml", UriKind.Relative));
        }


        private void searchClick(object sender, RoutedEventArgs e)
        {
            ResultBox.ItemsSource = App.AllDataModel.getSearch(searchText.Text);
        }
        // Initializes the synthesizer object and two recognizer objects
        private void InitializeSpeech()
        {
            speechOutput = new SpeechSynthesizer();

            // Simple dictation recognizer for filling in memo text
            speechInput = new SpeechRecognizerUI();

            // Set text to display to the user when recognizing
            speechInput.Settings.ExampleText = "Example: \"Magazine\"";
            speechInput.Settings.ListenText = "Say your word";



            // Recognizer for getting commands on this page
            commandReco = new SpeechRecognizerUI();


            // Note: Grammars are intialized in the InitCommandGrammars method
        }

        // Recursively crawls through the tree of controls to find all button controls and adds the Content text
        // to a List.
        public static void GetButtonContentText(UIElement uiElement, IList<string> buttonNames)
        {
            Button button = uiElement as Button;
            if (button != null && button.Content != null && !String.IsNullOrEmpty(button.Content.ToString()))
            {
                buttonNames.Add(button.Content.ToString()); // TODO: check to make sure the Content is not a non-text object
            }

            Panel panel = uiElement as Panel;

            if (panel != null)
            {
                foreach (UIElement child in panel.Children)
                {
                    GetButtonContentText(child, buttonNames);
                }
            }
        }
        // Initializes the grammar used by the commandReco recognizer object
        private void InitializeCommandGrammar()
        {
            // Recursively add "Content" text of each button to the mainPageCommands string list
            GetButtonContentText(this.LayoutRoot, mainPageCommands);

            // Add these three commands that don't have buttons to the mainPageCommands string array
            mainPageCommands.Add("Try again");
            mainPageCommands.Add("Quit");
            mainPageCommands.Add("Save and try again");

            // Add grammar consisting of button "Content" text
            commandReco.Recognizer.Grammars.AddGrammarFromList("mainPageCommands", mainPageCommands);
        }

        // Handler for mic tap
        private void mic_Tap(object sender, RoutedEventArgs e)
        {
            // Get a new memo using speech recognition
            GetNewMemoByVoice();
        }
        private async void GetCommand()
        {
            // Prompt the user to say a command
            await speechOutput.SpeakTextAsync("Say a button name, quit, 'save and try again' or 'try again'.");

            var operation = commandReco.RecognizeWithUIAsync();

            // Use a callback function instead of the await keyword in this case
            operation.Completed = CommandCompleted;
        }
        private void CommandCompleted(IAsyncOperation<SpeechRecognitionUIResult> asyncInfo, AsyncStatus asyncStatus)
        {
            // Don't do anything if the recognition hasn't completed.
            if (asyncStatus != AsyncStatus.Completed)
            {
                return;
            }

            try
            {
                // Get the recognition result object
                SpeechRecognitionUIResult result = asyncInfo.GetResults();

                if (result.ResultStatus != SpeechRecognitionUIStatus.Succeeded) // 
                {

                    // Return if not successful. This is a shortcut. A real application would take appropriate action depending 
                    // on the status
                    this.Dispatcher.BeginInvoke(delegate { MessageBox.Show("An error occurred in speech recognition."); });
                    return;
                }

                // Recognition successful -- take the action specified by the user
                System.Diagnostics.Debug.WriteLine(result.RecognitionResult.Text.ToLower());

            }
            catch (Exception ex)
            {
                this.Dispatcher.BeginInvoke(delegate { MessageBox.Show("Exception in command recognition handler " + ex.Message); });
            }
        }

        // Gets a new memo using recognition. Used by mic_Tap handler and some command results
        // in the CommandCompleted callback
        private async void GetNewMemoByVoice()
        {
            try
            {
                // Prompt the user using speech synthesis
                await speechOutput.SpeakTextAsync("Say your word");

                // Use the default dictation grammar to get the new memo text
                var recoResult = await speechInput.RecognizeWithUIAsync();

                if (recoResult.ResultStatus == SpeechRecognitionUIStatus.Succeeded)
                {
                    // Show new memo text
                    //Utilities.SetTextBoxTextSafely(Memo_TB, recoResult.RecognitionResult.Text);
                    string s = recoResult.RecognitionResult.Text; 
                    s = s.Replace(".", "");
                    searchText.Text = s;
                    ResultBox.ItemsSource = App.AllDataModel.getSearch(searchText.Text);
                    
                }
                else
                {
                    this.Dispatcher.BeginInvoke(delegate { MessageBox.Show(String.Format("Failure message: {0}", recoResult.ResultStatus.ToString())); });
                }
            }
            catch (Exception ex)
            {
                const int privacyPolicyHResult = unchecked((int)0x80045509);

                if (ex.HResult == privacyPolicyHResult) // User has not accepted the speech privacy policy
                {
                    this.Dispatcher.BeginInvoke(delegate { MessageBox.Show("The user has not accepted the speech privacy policy."); });
                }
                else
                {
                    this.Dispatcher.BeginInvoke(delegate { MessageBox.Show("Exception in dictation recognition" + ex.Message); });
                }
            }
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            GetNewMemoByVoice();

        }



    }
}